package com.adayo.memoryfree.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.adayo.memoryfree.utils.DialogMaker;
import com.adayo.memoryfree.utils.JLogKit;

import org.xutils.x;

public abstract class FragmentBase extends Fragment {

	protected Activity context;
	protected Dialog dialog;
	protected boolean isVisibleToUser = true;
	protected View view;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = getActivity();
		initParams(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		view = x.view().inject(this, inflater, container);
		initWidgets();
		return view;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		this.isVisibleToUser = isVisibleToUser;
	}

	protected void initParams(Bundle savedInstanceState) {
	}

	protected abstract void initWidgets();

	/**
	 * pop dialog
	 *
	 * @param title
	 * @param msg
	 * @param btns
	 * @param isCanCancelabel
	 * @param isDismissAfterClickBtn
	 * @return
	 */
	public Dialog showAlertDialog(String title, String msg, String[] btns,
								  boolean isCanCancelabel, final boolean isDismissAfterClickBtn,
								  Object tag) {
		if (null == dialog || !dialog.isShowing()) {
			JLogKit.getInstance().i("show alert dialog");
			DialogMaker.showCommonAlertDialog(context, title, msg, btns, null,
					isCanCancelabel, isDismissAfterClickBtn, tag);
		}
		return dialog;
	}

	public Dialog showWaitDialog(String msg, boolean isCanCancelabel, Object tag) {
		if (null == dialog || !dialog.isShowing()) {
			JLogKit.getInstance().i("show wait dialog");
			dialog = DialogMaker.showCommonWaitDialog(context, msg, null,
					isCanCancelabel, tag);
		}
		return dialog;
	}

	/**
	 * close dialog
	 */
	public void dismissDialog() {
		if (null != dialog && dialog.isShowing()) {
			JLogKit.getInstance().i("dismiss dialog");
			dialog.dismiss();
		}
	}

	@Override
	public void onDestroyView() {
		dismissDialog();
		super.onDestroyView();
	}

	protected void startActivity(Class<?> cls, Intent intent) {
		if(null == intent){
			intent = new Intent(context, cls);
		}
		startActivity(intent);
	}
}
